﻿using LeafAssist;
using System;
using System.ComponentModel;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace PlatformDemo.Demo.Token
{
    public partial class RequestToken : UserControl
    {
        public RequestToken()
        {
            InitializeComponent();

            propertyGrid.SelectedObject = new Parameter();

            textBoxBaseUrl.Text = GlobalVariable.BaseUrl;
            textBoxBaseAddr.Text = GlobalVariable.BaseRoute["RequestToken"];

            buttonAccess.Click += (object sender, EventArgs eventArgs) =>
            {
                Parameter parameter = propertyGrid.SelectedObject as Parameter;

                var httpRequest = new HttpRequest();

                var urlParams = new RequestParams
                {
                    ["Username"] = parameter.UserName,
                    ["Password"] = parameter.PassWord,
                };

                string url = string.Format("{0}{1}", textBoxBaseUrl.Text, textBoxBaseAddr.Text);

                httpRequest.UserAgent = Http.FirefoxUserAgent();

                new Thread(Action =>
                {
                    Application.DoEvents();
                    textBoxResult.Invoke(new Action(() =>
                    {
                        HttpResponse httpResponse = httpRequest.Get(url, urlParams);

                        switch (httpResponse.StatusCode)
                        {
                            case HttpStatusCode.OK:
                                labelHttpStatus.ForeColor = Color.Green;
                                textBoxResult.Text = httpResponse.ToString();
                                GlobalVariable.Token = JsonNewtonsoft.FromJSON<PlatformDemo.Token>(httpResponse.ToString());
                                break;
                            default:
                                labelHttpStatus.ForeColor = Color.Red;
                                break;
                        }

                        labelHttpStatus.Text = $"响应码: {(int)httpResponse.StatusCode}";
                        
                    }));
                }).Start();                
            };
        }
    }

    public class Parameter
    {
        [Category("参数")]
        [Description("在网站中注册的用户名称或者邮箱地址")]
        [DisplayName("用户名称")]
        public string UserName { get; set; } = GlobalVariable.UserName;

        [Category("参数")]
        [Description("在网站中注册的时所设置的密码")]
        [DisplayName("登陆密码")]
        public string PassWord { get; set; } = GlobalVariable.PassWord;
    }

    public class TokenInterface : Interface
    {
        public string Name => "获取令牌";

        public string Category => "令牌";

        public Control CreatePanel()
        {
            return new RequestToken();
        }
    }
}
